﻿#region << 文 件 说 明 >>

/*----------------------------------------------------------------
// 文件名称：LoadingContainer
// 创 建 人：YangCheng
// 创建时间：2022/6/30 17:20:46
// 文件版本：V1.0.0
// ===============================================================
// 功能描述：
//
//
//----------------------------------------------------------------*/

#endregion

namespace Vampirewal.Core.WPF.Theme;

/// <summary>
///
/// </summary>
public class LoadingContainer : ContentControl
{
    public LoadingContainer()
    {
        //构造函数
    }

    private Storyboard _sbOnloading;
    private Border _maskContainer;

    static LoadingContainer()
    {
        DefaultStyleKeyProperty.OverrideMetadata(typeof(LoadingContainer), new FrameworkPropertyMetadata(typeof(LoadingContainer)));
    }

    public override void OnApplyTemplate()
    {
        base.OnApplyTemplate();
        if (Template.Resources["OnLoading"] is Storyboard sb
            && Template.FindName("MaskDG", this) is Border gd)
        {
            _sbOnloading = sb;
            _maskContainer = gd;
            _maskContainer.Visibility = Visibility.Hidden;
        }
    }

    #region Properties

    public string LoadingTips
    {
        get { return (string)GetValue(LoadingTipsProperty); }
        set { SetValue(LoadingTipsProperty, value); }
    }

    // Using a DependencyProperty as the backing store for LoadingTips.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty LoadingTipsProperty =
        DependencyProperty.Register("LoadingTips", typeof(string), typeof(LoadingContainer), new PropertyMetadata("加载中，请稍等"));

    public bool OnLoading
    {
        get { return (bool)GetValue(OnLoadingProperty); }
        set { SetValue(OnLoadingProperty, value); }
    }

    // Using a DependencyProperty as the backing store for OnLoading.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty OnLoadingProperty =
        DependencyProperty.Register("OnLoading", typeof(bool), typeof(LoadingContainer), new PropertyMetadata(OnloadingCallback));

    private static void OnloadingCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        if (d is LoadingContainer fl)
        {
            if (e.NewValue.Equals(true))
                fl.StartupOnLoading();
            else
                fl.StopOnLoading();
        }
    }

    #endregion

    #region Tools

    private void StartupOnLoading()
    {
        if (_sbOnloading != null)
        {
            _maskContainer.Visibility = Visibility.Visible;
            _sbOnloading.Begin(_maskContainer);
        }
    }

    private void StopOnLoading()
    {
        if (_sbOnloading != null)
        {
            _sbOnloading.Stop(_maskContainer);
            _maskContainer.Visibility = Visibility.Hidden;
        }
    }

    #endregion
}